﻿using Temporalio.Client;
using Temporalio.Worker;

namespace APMService
{
    public class WorkerService : BackgroundService
    {
        private readonly TemporalClient _client;
        private readonly ILogger<WorkerService> _logger;
        private TemporalWorker _worker;
        private APMActivities _activities;

        public WorkerService(TemporalClient client, ILogger<WorkerService> logger, APMActivities activities)
        {
            _client = client;
            _logger = logger;
            _activities = activities;

            var workerOptions = new TemporalWorkerOptions(taskQueue: "apm-queue")
                .AddAllActivities(activities)
                .AddWorkflow<APMWorkflow>();

            _worker = new TemporalWorker(_client, workerOptions);
            _worker.Options.MaxConcurrentActivities = 1;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Temporal Worker starting...");

            try
            {
                await _worker.ExecuteAsync(stoppingToken);
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("Worker execution was canceled");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Worker execution failed. Error description");
            }
            finally
            {
                _logger.LogInformation("Temporal Worker stopped");
            }
        }
    }
}
